package com.jindouyun.common.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import java.time.LocalDateTime;

/**
 * @className: com.jindouyun.common.entity.JDYResponse
 * @description: 筋斗云RPC请求实体类封装
 * @author: tong.li
 * @createTime: 2021/10/12 15:16
 * @copyright: Tongcheng-Elong Holdings Limited
 */
@Data
public class JDYResponse<T> {

    /**
     * 私有化构造，从静态方法创建
     */
    private JDYResponse() {}

    /**
     * 全局唯一，每次请求ID会原路返回到这个字段
     */
    private String requestId;

    /**
     * 响应码
     */
    private int code;

    /**
     * 响应数据
     */
    private T data;

    /**
     * 响应消息
     */
    private String message;

    /**
     * 响应时间戳
     */
    private LocalDateTime timestamp;


    public static<T> JDYResponse buildResponse(String requestId, T data, String message, ResponseCodeEnums codeEnum) {
        JDYResponse response = new JDYResponse();
        response.requestId = requestId;
        response.timestamp = LocalDateTime.now();
        response.data = data;
        response.code = codeEnum.code;
        response.message = (message == null || message.length() == 0) ? codeEnum.desc : message;
        return response;
    }

    public static<T> JDYResponse ok(String requestId, T data) {
        return JDYResponse.buildResponse(requestId, data, null, ResponseCodeEnums.OK);
    }

    public static<T> JDYResponse fail(String requestId, String message) {
        return JDYResponse.buildResponse(requestId, null, message, ResponseCodeEnums.ERROR);
    }


    /**
     * @enumName: com.jindouyun.common.entity.JDYResponse.ResponseCode
     * @description: 响应码枚举
     * @author: tong.li
     * @createTime: 2021/10/12 15:16
     * @copyright: Tongcheng-Elong Holdings Limited
     */
    @AllArgsConstructor
    public enum ResponseCodeEnums {

        OK(00000,"请求成功"),

        ERROR(99999,"请求失败"),
        ;

        /**
         * 响应码
         */
        @Getter
        private int  code;
        /**
         * 响应码描述
         */
        @Getter
        private String desc;

    }

}
